package cn.unuuc.cwl.order.service;

import cn.unuuc.cwl.order.entity.Order;
import cn.unuuc.cwl.order.mapper.OrderMapper;
import cn.unuuc.cwl.order.model.OrderQo;
import cn.unuuc.cwl.order.model.qo.AccountQo;
import cn.unuuc.cwl.order.model.qo.StorageQo;
import cn.unuuc.cwl.order.service.openfeign.AccountOpenFeignService;
import cn.unuuc.cwl.order.service.openfeign.StorageOpenFeignService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalLock;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class OrderService extends ServiceImpl<OrderMapper, Order> {


    @Resource
    private AccountOpenFeignService accountOpenFeignService;

    @Resource
    private StorageOpenFeignService storageOpenFeignService;


    @GlobalLock
    @GlobalTransactional
    public String saveOrder(OrderQo orderQo) {
        log.info("调用库存模块，减少库存");
        StorageQo storageQo = new StorageQo();
        storageQo.setStorageId(Long.valueOf(orderQo.getStorageId()));
        storageQo.setDeductNum(orderQo.getGoodsNum());
        String storageResult = storageOpenFeignService.deductStorage(storageQo);
        log.info("库存模块服务返回信息:{}", storageResult);
        System.out.println("\n\n");
        log.info("调用用户模块，减少余额");
        AccountQo accountQo = new AccountQo();
        accountQo.setAccount(orderQo.getAccount());
        accountQo.setDeductMoney((double) (orderQo.getGoodsNum() * 2));
        String accountResult = accountOpenFeignService.deductMoney(accountQo);
        log.info("调用用户模块返回信息:{}", accountResult);
        System.out.println("\n\n");

        log.info("保存订单信息");
        Order order = new Order();
        order.setAccount(orderQo.getAccount());
        order.setStorageId(orderQo.getStorageId());
        this.baseMapper.insert(order);
        log.info("订单保存成功");
        return "订单保存成功";
    }

}
